package com.study.system.eduadservice.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * 更新广告的任务
 */
@Component
public class UpdateAdTask {

    private Logger logger = LoggerFactory.getLogger(UpdateAdTask.class);

    /**
     * 更新广告
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void updateAd() throws IOException {
        //创建URL对象
        URL url = new URL("http://localhost:8888/ad_update?sid=1");
        //创建http连接对象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置连接超时
        conn.setConnectTimeout(2000);
        //设置内容类型
        conn.addRequestProperty("Content-Type","application/json;charset=utf-8");
        //获得网络输入流
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        StringBuilder stringBuilder = new StringBuilder();
        //逐行读取文字
        while((line = reader.readLine()) != null){
            stringBuilder.append(line);
        }
        reader.close();
        conn.disconnect();
        logger.info("广告更新成功！" + stringBuilder);
    }
}
